package com.example.smartcity_poverty.ui.PersonalCenter.activity

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import androidx.core.widget.addTextChangedListener
import com.example.smartcity_poverty.R
import com.example.smartcity_poverty.logic.network.AppApi
import com.example.smartcity_poverty.logic.network.ServiceNET.Companion.create
import com.example.smartcity_poverty.logic.util.Util.show
import kotlinx.android.synthetic.main.activity_new_content.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject

class NewContentActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        setContentView(R.layout.activity_new_content)
        title = "意见反馈"

        newContent2.addTextChangedListener {
            val len = it?.length.toString() + "/150"
            newContentLength.text = len
        }


        // 提交反馈
        newContentOk.setOnClickListener {
            if (newContent1.text.isEmpty() && newContent2.text.isEmpty()) "不能为空！".show()
            else {
                getSharedPreferences("token", Context.MODE_PRIVATE).apply {
                    val token = getString("token", "").toString()
                    GlobalScope.launch(Dispatchers.Main){
                        create<AppApi>().newContent(token, JSONObject().apply {
                            put("title", newContent1.text.toString())
                            put("content", newContent2.text.toString())
                        }.toString().toRequestBody("application/json".toMediaTypeOrNull())).apply {
                            if (this.code == "200"){
                                runOnUiThread {
                                    newContent1.setText("")
                                    newContent2.setText("")
                                    this.msg.show()

                                }
                            }else runOnUiThread { this.msg.show() }
                        }
                    }
                }
            }
        }

    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        finish()
        return super.onOptionsItemSelected(item)
    }
}